﻿/* ***********************************************
 * Author		:  kingthy
 * Email		:  kingthy@gmail.com
 * Description	:  OAuth授权对象
 *
 * ***********************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Specialized;
using OpenTwitter.SDK.Http;
using System.Web;
using OpenTwitter.SDK.Tencent.Objects;

namespace OpenTwitter.SDK.Sina
{
    /// <summary>
    /// OAuth授权对象
    /// </summary>
    public class OAuth : OAuthBase
    {
        /// <summary>
        /// 根据app_key与app_secret实例化
        /// </summary>
        public OAuth(string appKey, string appSecret)
            : base(appKey, appSecret)
        { }

        /// <summary>
        /// 新浪的Oauth请求是POST请求
        /// </summary>
        protected override RequestMethod RequestMethod
        {
            get
            {
                return RequestMethod.POST;
            }
        }
        /// <summary>
        /// 使用默认的API地址同步获取未授权的Request Token. 
        /// 如果获取成功, 对象实例的Token与TokenSecret属性值将改为request_token与request_secret
        /// </summary>
        /// <param name="callback">返回地址, 如果为空或NULL值则获取PIN码</param>
        /// <returns>是否获取request token成功</returns>
        public bool GetRequestToken(string callback)
        {
            return this.GetRequestToken("http://api.t.sina.com.cn/oauth/request_token", callback);
        }

        /// <summary>
        /// 使用默认的API地址同步获取授权的Access Token，调用此方法时必须设置Token与TokenSecret属性的值为request_token与request_secret
        /// 如果获取成功, 对象实例的Token与TokenSecret属性值将改为access_token与access_secret
        /// </summary>
        /// <param name="verifier">请求授权request token时返回的验证码</param>
        /// <param name="user">微博帐户(key=帐户id, value=帐户名)</param>
        /// <returns>是否获取Access Token成功</returns>
        public bool GetAccessToken(string verifier, out AuthorizedUser user)
        {
            NameValueCollection responseData;
            var r = this.GetAccessToken("http://api.t.sina.com.cn/oauth/access_token", verifier, out responseData);
            string userId = r && responseData != null ? responseData["user_id"] : null;
            string name = r && responseData != null ? responseData["screen_name"] : null;

            if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(userId))
            {
                user = null;
            }
            else
            {
                user = new AuthorizedUser(userId, name);
            }

            return r;
        }
    }
}
